<template>
  <view>
    <scroll-view
      :scroll-y="modalName == null"
      class="page"
      :class="modalName != null ? 'show' : ''"
    >
      <cu-custom class="custom-nav">
        <block slot="left">
          <view @tap="goback">
            <text>返回</text>
          </view>
        </block>
        <block slot="content">XX轨迹详情</block>
        <block slot="right">
          <view @tap="changeStatus" data-target="DialogModal1">
            <text>修改状态</text>
          </view>
        </block>
      </cu-custom>
      <!-- 轨迹回放 -->
      <view id="container" class="container"></view>
    </scroll-view>
    <!-- 弹窗 -->
    <Modal
      class="modelist"
      :modalName="modalName"
      :modalData="modalData"
      :title="title"
      @hideModal="hideModal"
      :showFlag="showFlag"
      :isShowBtn="false"
    ></Modal>

    <!-- 事件处理弹窗 -->
    <view
      class="cu-modal msgDialog"
      :class="modalName1 == 'DialogModal1' ? 'show' : ''"
    >
      <view class="cu-dialog">
        <view class="cu-bar bg-title justify-end">
          <view class="content">提示</view>
          <view class="action" @tap="hideModal">
            <text
              class="cuIcon-close text-white"
              style="font-weight: 700"
            ></text>
          </view>
        </view>
        <view class="padding-xl">
          <!-- Modal 内容。 -->
          <text>将此事件设置为</text
          ><text style="font-size: 18px; font-weight: 700"
            >【{{ status == 0 ? "已确认" : "待确认" }}】</text
          >状态
        </view>
        <view class="cu-bar bg-white justify-center">
          <view class="action">
            <button class="cu-btn bg-red" @tap="hideModal">取消</button>
            <button class="cu-btn bg-blue margin-left" @tap="hideModal">
              确定
            </button>
          </view>
        </view>
      </view>
    </view>
    <!-- 控件 -->
    <div class="contron_box">
      <div
        v-for="item in control_list"
        :key="item.index"
        class="c_items"
        @tap="getControl(item)"
      >
        <view style="font-size: 16px" :class="['cuIcon-' + item.cuIcon]"></view>
        <p>{{ item.name }}</p>
      </div>
    </div>
  </view>
</template>

<script>
import Modal from "../home/modal.vue";
export default {
  name: "track",
  components: {
    Modal,
  },
  data() {
    return {
      modalName: null,
      status: 0,
      map1: null,
      path: [],
      // 目标纬度
      latitude: "",
      // 目标经度
      longitude: "",
      // 目标地址名称
      name: "",
      // 目标地址详细信息
      address: "",
      // 我自己的位置经纬度（百度地图需要传入自己的经纬度进行导航）
      selfLocation: {
        latitude: "",
        longitude: "",
      },
      markerId: null,
      modalName1: "",
      title: "",
      modalData: [],
      showFlag: 2,
      randomCoords: [],
      reviewFlag: false,
      rePath: [],
      polyline: null,
      control_list: [
        {
          name: "回放",
          cuIcon: "share",
        },
      ],
    };
  },
  created() {
    console.log(this.$Router.getPageRoute(), "$Router");
    this.status = this.$Router.getPageRoute().query.status;
  },
  mounted() {
    const A_MAP_KEY = "1f520f629a5d77331f39101e3ba2ca7e"; // 地图key
    const A_MAP_SECRET_KEY = "1bdb81bea11b57789cb8954098488ba0"; // 地图密钥
    // 地图初始化
    const script = document.createElement("script");
    script.src = `https://webapi.amap.com/maps?v=1.4.15&key=${A_MAP_KEY}`;
    script.onload = this.initAmap.bind(this);
    document.head.appendChild(script);

    const script1 = document.createElement("script");
    // todo这里注意打包的时候如果是本地的话相对路径 如果放到服务器要用绝对路径 ./map
    // script1.src = "./map.js";
    script1.src = "../../map.js";
    script1.onload = this.initAmap.bind(this);
    document.head.appendChild(script1);
    // this.initAmap();
  },
  unmounted() {
    this.map1?.destroy();
  },
  methods: {
    goback() {
      // this.$Router.push({ name: "event" });
      uni.navigateBack({
        delta: 1,
      });
    },
    //初始化地图
    initAmap() {
      // todo 这里的baseurl 是瓦片地图的图层 根据服务器来 后面要动态获取服务器的地址
      // let base_url = "http://192.168.10.99:3000";
      let base_url = "http://localhost:3000";
      const customLayer = [
        new AMap.TileLayer({
          getTileUrl: function (x, y, z) {
            return `${base_url}/city/${z}/${x}/${y}.jpg`;
          },
          opacity: 1,
          zIndex: 99,
        }),
      ];
      this.map1 = new AMap.Map("container", {
        zoom: 12,
        resizeEnable: true,
        defaultCursor: "pointer",
        showLabel: true, //是否显示文字标注
        center: [114.4293, 30.5162],
        layers: customLayer,
      });
      this.map1.add(customLayer);
      AMap.plugin(["AMap.ToolBar", "AMap.Scale", "AMap.Driving"]);
      //添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
      this.map1.addControl(new AMap.ToolBar());

      //添加比例尺控件，展示地图在当前层级和纬度下的比例尺
      this.map1.addControl(new AMap.Scale());
      this.manyPersonWays();
    },
    // 修改状态
    changeStatus(e) {
      this.modalName1 = e.currentTarget.dataset.target;
    },
    hideModal() {
      this.modalName1 = null;
      this.modalName = null;
    },
    manyPersonWays() {
      const _this = this;
      let id = 0;
      // 洪山区边界坐标（示例）
      var hongshanBounds = {
        minLat: 30.4852,
        maxLat: 30.5636,
        minLng: 114.3355,
        maxLng: 114.4176,
      };

      // 在地图上绘制路径
      function drawPath(coords) {
        var path = [];
        var startPoint = null;
        var passPoints = [];
        for (var i = 0; i < coords.length; i++) {
          var lngLat = new AMap.LngLat(coords[i].lng, coords[i].lat);
          path.push(lngLat);
          _this.rePath = path;
          if (_this.reviewFlag) {
            // 在这实现一个动态轨迹播放的功能 还有起始marker 和途径marker
            dynamicPlayback(_this.rePath);
            console.log(111);
          } else {
            // 添加起始点标记
            if (i === 0) {
              startPoint = lngLat;
              addMarker(startPoint, "start");
            }

            // 添加途经点标记
            if (i > 0 && i < coords.length - 1) {
              passPoints.push(lngLat);
              addMarker(lngLat, "pass");
            }
            // 绘制路径
            if (i === coords.length - 1) {
              addMarker(lngLat, "end");
              firstDraw(path);
            }
            firstDraw(path);
          }
        }
        _this.map1.setFitView();
      }
      function firstDraw(path) {
        _this.polyline = new AMap.Polyline({
          path: path, // 将所有路径数组拼接为一个路径数组
          showDir: true,
          isOutline: true,
          outlineColor: "#ffeeee",
          borderWeight: 2,
          strokeColor: "#fd3e4a", // 使用不同的深色区分不同的轨迹
          strokeWeight: 6,
          lineJoin: "round",
          lineCap: "round",
        });
        _this.map1.add(_this.polyline);
      }
      // 添加标记
      function addMarker(lngLat, type) {
        var icon;
        if (type === "start") {
          icon = "../../static/mapImg/start.png";
        } else if (type === "pass") {
          icon = "../../static/mapImg/mid.png";
        } else {
          icon = "../../static/mapImg/end.png";
        }
        var marker = new AMap.Marker({
          position: lngLat,
          icon: icon,
          map: _this.map1,
          id: id++,
        });
        AMap.event.addListener(marker, "click", function (e) {
          handleMarker(e);
        });
      }
      // 处理marker 点击
      function handleMarker(e) {
        if (e.target.CLASS_NAME === "AMap.Marker") {
          var marker = e.target;
          _this.title = `目标ID：${marker.w.id}`;
          // 用户相关配置放到marker
          _this.markerId = marker.w.id++;
          // 打开模态框
          _this.modalName = "bottomModal";
          // 添加信息窗体
          var infoWindow1 = new AMap.InfoWindow({
            offset: new AMap.Pixel(-1, -35),
            content: `<div style="text-align:left;" >批号：${
              _this.markerId
            }</div><div style="text-align:left;" >方位：${
              marker.getPosition().lat
            }</div>`,
          });
          _this.modalData = [
            { name: "目标名称", value: marker.w.id },
            { name: "频       段", value: "xxxx" },
            { name: "距       离", value: "xxxx" },
            { name: "检测类型", value: "默认(融合后)" },
            { name: "方       位", value: "xxxx" },
            { name: "所属区域", value: "区域一" },
            {
              name: "经       度",
              value:
                marker.showDuFenMiao == "du"
                  ? decimalToDMS(marker.getPosition().lng)
                  : marker.getPosition().lng,
            }, // 实时经度
            {
              name: "维       度",
              value:
                marker.showDuFenMiao == "du"
                  ? decimalToDMS(marker.getPosition().lat)
                  : marker.getPosition().lat,
            }, // 实时纬度
            { name: "目标类型", value: "白名单目标" },
          ];
          // 设置信息窗体的内容
          function setInfoWindowContent(marker) {
            infoWindow1.open(_this.map1, marker.getPosition());
          }
          setInfoWindowContent(marker);
        }
      }
      // 生成随机坐标并绘制路径
      _this.randomCoords = generateRandomCoords();
      // 判断是不是缓存数据 这里后续会换成真实数据 就不用缓存了
      if (this.reviewFlag) {
        drawPath(_this.rePath);
      } else {
        drawPath(_this.randomCoords);
      }
      // 生成随机经纬度坐标
      function generateRandomCoords() {
        var coords = [];
        for (var i = 0; i < 10; i++) {
          var lat =
            Math.random() * (hongshanBounds.maxLat - hongshanBounds.minLat) +
            hongshanBounds.minLat;
          var lng =
            Math.random() * (hongshanBounds.maxLng - hongshanBounds.minLng) +
            hongshanBounds.minLng;
          coords.push({ lat: lat, lng: lng });
        }
        return coords;
      }
      // 实现动态轨迹播放功能
      function dynamicPlayback(path) {
        _this.map1.clearMap(); // 清除地图上的所有覆盖物
        var polyline1 = null; // 用于存储轨迹线对象
        var i = 0;
        var interval = 1000; // 每个轨迹点之间的间隔时间，单位为毫秒
        var timer = setInterval(function () {
          if (i < path.length) {
            var lngLat = new AMap.LngLat(path[i].lng, path[i].lat);
            // 添加起始点标记
            if (i === 0) {
              addMarker(lngLat, "start");
            }
            // 添加途经点标记
            else if (i < path.length - 1) {
              addMarker(lngLat, "pass");
            }
            // firstDraw(lngLat);
            // 移动地图视角到当前轨迹点
            // 绘制轨迹
            if (i > 0) {
              var pathCoords = path.slice(0, i + 1).map(function (point) {
                return [point.lng, point.lat];
              });
              if (polyline1) {
                polyline1.setPath(pathCoords);
              } else {
                polyline1 = new AMap.Polyline({
                  map: _this.map1,
                  path: pathCoords,
                  showDir: true,
                  isOutline: true,
                  outlineColor: "#ffeeee",
                  borderWeight: 2,
                  strokeColor: "#fd3e4a", // 使用不同的深色区分不同的轨迹
                  strokeWeight: 6,
                  lineJoin: "round",
                  lineCap: "round",
                });
              }
            }
            _this.map1.setCenter(path[i]);
            i++;
          } else {
            // 所有轨迹点已经播放完毕，添加终点标记并清除定时器
            addMarker(
              new AMap.LngLat(
                path[path.length - 1].lng,
                path[path.length - 1].lat
              ),
              "end"
            );
            clearInterval(timer);
          }
        }, interval);
      }
    },
    handleNavigation() {
      const _this = this;
      if (!this.latitude || !this.longitude || !this.name) return;
      // 微信
      // #ifdef MP-WEIXIN
      let _obj = {
        latitude: parseFloat(this.latitude),
        longitude: parseFloat(this.longitude),
        name: this.name,
      };
      if (this.address) {
        _obj["address"] = this.address;
      }
      uni.openLocation({
        ..._obj,
        success: function (res) {
          console.log("打开系统位置地图成功");
        },
        fail: function (error) {
          console.log(error);
        },
      });
      // #endif

      // #ifdef APP-PLUS
      // 判断系统安装的地图应用有哪些, 并生成菜单按钮
      let _mapName = [
        {
          title: "高德地图",
          name: "amap",
          androidName: "com.autonavi.minimap",
          iosName: "iosamap://",
        },
        {
          title: "百度地图",
          name: "baidumap",
          androidName: "com.baidu.BaiduMap",
          iosName: "baidumap://",
        },
        {
          title: "腾讯地图",
          name: "qqmap",
          androidName: "com.tencent.map",
          iosName: "qqmap://",
        },
      ];
      // 根据真机有的地图软件 生成的 操作菜单
      let buttons = [];
      let platform = uni.getSystemInfoSync().platform;
      platform === "android" &&
        _mapName.forEach((item) => {
          if (plus.runtime.isApplicationExist({ pname: item.androidName })) {
            buttons.push(item);
          }
        });
      platform === "ios" &&
        _mapName.forEach((item) => {
          console.log(item.iosName);
          if (plus.runtime.isApplicationExist({ action: item.iosName })) {
            buttons.push(item);
          }
        });
      if (buttons.length) {
        plus.nativeUI.actionSheet(
          {
            //选择菜单
            title: "选择地图应用",
            cancel: "取消",
            buttons: buttons,
          },
          function (e) {
            let _map = buttons[e.index - 1];
            _this.openURL(_map, platform);
          }
        );
      } else {
        uni.showToast({
          title: "请安装地图软件",
          icon: "none",
        });
        return;
      }
      // #endif
    },
    // 回放
    getControl() {
      // 清除地图上的点位和轨迹
      this.reviewFlag = true;
      if (this.polyline) {
        this.map1.remove(this.polyline);
        this.polyline = null; // 清除引用
      }
      this.map1.clearMap();
      this.manyPersonWays();
    },
    // 打开第三方程序实际应用
    openURL(map, platform) {
      let _defaultUrl = {
        android: {
          amap: `amapuri://route/plan/?sid=&did=&dlat=${this.latitude}&dlon=${this.longitude}&dname=${this.name}&dev=0&t=0`,
          qqmap: `qqmap://map/routeplan?type=drive&to=${this.name}&tocoord=${this.latitude},${this.longitude}&referer=fuxishan_uni_client`,
          baidumap: `baidumap://map/direction?origin=${this.selfLocation.latitude},${this.selfLocation.longitude}&destination=name:${this.name}|latlng:${this.latitude},${this.longitude}&coord_type=wgs84&mode=driving&src=andr.baidu.openAPIdemo"`,
        },
        ios: {
          amap: `iosamap://path?sourceApplication=fuxishan_uni_client&dlat=${this.latitude}&dlon=${this.longitude}&dname=${this.name}&dev=0&t=0`,
          qqmap: `qqmap://map/routeplan?type=drive&to=${this.name}&tocoord=${this.latitude},${this.longitude}&referer=fuxishan_uni_client`,
          baidumap: `baidumap://map/direction?origin=${this.selfLocation.latitude},${this.selfLocation.longitude}&destination=name:${this.name}|latlng:${this.latitude},${this.longitude}&mode=driving&src=ios.baidu.openAPIdemo`,
        },
      };
      let newurl = encodeURI(_defaultUrl[platform][map.name]);
      console.log(newurl);
      plus.runtime.openURL(
        newurl,
        function (res) {
          console.log(res);
          uni.showModal({
            content: res.message,
          });
        },
        map.androidName ? map.androidName : ""
      );
    },
  },
};
</script>

<style scoped>
.modelist {
  z-index: 100;
  background-color: transparent;
  /* height: 35%; */
  position: fixed !important;
  left: 0 !important;
  top: 60% !important;
  overflow: auto;
}
.contron_box {
  width: 32px;
  /* height: 100px; */
  position: fixed;
  right: 18px;
  top: 80px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  text-align: center;
  overflow: hidden;
  background-color: rgba(206, 202, 202, 0.8);
  /* 调整透明度为 0.5 */
  border-radius: 5px;
  padding: 10px 0 0 0;
}
.c_items {
  width: 32px;
  height: 40px;
  font-size: 12px;
  color: #000;
  font-weight: 500;
}
css .notification {
  display: inline-block;
  position: relative;
}
.page {
  height: 100vh;
  width: 100vw;
  position: relative;
}

.page.show {
  overflow: hidden;
}
.custom-nav,
.cu-bar.fixed {
  color: aliceblue;
}
.cu-item {
  background-color: #fff;
  margin-bottom: 10px;
  border-radius: 5px;
}
#container {
  height: 100vh;
  width: 100vw;
}
::v-deep .amap-touch-toolbar .amap-zoomcontrol {
  position: absolute;
  bottom: 600px !important;
}
.content_bottom {
  display: flex;
  flex-wrap: wrap;
  padding: 15px;
}
.cu-list {
  margin: 10px 17px;
}
.c-item {
  width: 45%;
  padding: 5px 0;
  /* margin: 5px 0; */
  text-align: left;
}
.cu-item1 {
  position: relative;
}
.cu-tag1 {
  position: absolute;
  top: 2px;
  left: 0;
}
.ml15 {
  margin-left: 35px;
}
.por20 {
  position: absolute;
  right: 20px;
  top: 70px;
}
</style>
